<template>
  <div id="devicePosition" style="width:100vw; height:80vh;display: flex;">
    <div id="divBox" style="height: 100%;width: 100%;margin-left: 20px;">
      <div id="playWnd" class="playWnd" style="height:80vh;position: fixed;">
      </div>
    </div>
  </div>
</template>
<script>
import $ from "jquery";
import {getCameraInfo, getEquipmentTree, getHkPtInfo,} from "@/api/web/equipment_manage";

export default {
  name: "live",
  data() {
    return {
      loading: false,
      showTimeDiv: false,
      showDivInstruction: false,
      playBackDateValue: "",
      buttonClick: 1,
      filterText: "",
      treeDataList: [],
      oWebControl: {
        JS_SetWindowControlCallback: null,
        JS_RequestInterface: null,
        JS_CreateWnd: null,
        JS_StartService: null,
      },
      pubKey: "",
      initCount: 0,
      tree_width: 4,
      tree_height_px: null,
      playMode: 0,
      JsonParam: {
        argument: {
          appkey: null,
          ip: null,
          port: null,
          secret: null,
          enableHTTPS: 1,
          language: "zh_CN",
          layout: "2x2",
          playMode: 0,
          reconnectDuration: 5,
          reconnectTimes: 5,
          showSmart: 0,
          showToolbar: 1,
          toolBarButtonIDs:
              "2048,2049,2050,2304,2306,2305,2307,2308,2309,4096,4608,4097,4099,4098,4609,4100",
          snapDir: "D:/snap",
          videoDir: "D:/video",
        },
        funcName: "init",
      },
      startParam: {
        argument: {
          authUuid: "asdafasdas",
          cameraIndexCode: "54774dcc7b2a4da385232d3de7098b1e",
          ezvizDirect: 0,
          gpuMode: 0,
          streamMode: 1,
          transMode: 1,
          wndId: -1,
          cascade: 1,
        },
        funcName: "startPreview",
      },
      startBackParam: {
        funcName: "startPlayback",
        argument: {
          cameraIndexCode: "", // 监控点编号
          startTimeStamp: "2022-08-01 12:00:00", // 录像查询开始时间戳，单位：秒
          endTimeStamp: "2022-08-04 12:00:00", // 录像查询结束时间戳，单位：秒
          recordLocation: 1, // 录像存储类型 0-中心存储 1-设备存储
          transMode: 1, // 传输协议 ，0-UDP 1-TCP
          gpuMode: 0, // 是否开启 GPU 硬解，0-不开启 1-开启
        },
      },
      indexCode: "",
    };
  },
  mounted() {
    const that = this;
    window.onresize = () => {
      return (() => {
        window.tree_height_px = document.body.clientHeight;
        let div = document.getElementById("divBox");
        const divH = div.clientHeight;
        const divW = div.clientWidth;
        that.oWebControl.JS_Resize(divW, divH);
        that.tree_height_px = window.tree_height_px;
      })();
    };
  },
  destroyed() {
    let _this = this;
    //跳转之后 销毁视频框
    _this.destroyWnd();
  },
  created() {
    const that = this;
    that.getHkPt().then((res) => {
      // that.initData();
    });
    that.loadJsFunc().then((res) => {
      setTimeout(() => {
        that.initPlugin();
      }, 200);
    });
  },
  props: {
    type: {
      type: String,
      require: true,
      default: "this",
    },
    cameraIndexCode: {
      type: String,
      required: false,
      default: null,
    },
    showToolbar: {
      type: Number,
      require: true,
      default: 1,
    },
  },
  computed: {},
  methods: {
    clickEvent: function (data) {
      if (data.type == "equipment") {
        // let params = {
        //   id: data.id,
        //   type: 1,
        // };
        // getRtspUrl(params).then((res) => {

        //   this.indexCode = res.resultMsg;
        // });
        this.startVideo(data.indexCode);
      }
    },
    contextMenuEvent: function (device, event, data, isCatalog) {
    },
    //获取参数
    getHkPt() {
      return new Promise((resolve, reject) => {
        let that = this;
        getHkPtInfo().then((res) => {
          let data = that.JsonParam.argument;
          let date = JSON.parse(JSON.stringify(data));
          date.appkey = res.data.accountNumber;
          date.ip = res.data.ipAddress;
          date.port = Number(res.data.equipmentPort);
          date.secret = res.data.accountPassword;
          that.JsonParam.argument = date;
          resolve("success");
        });
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //点击播放视频
    handleNodeClick(data) {
      if (data.type == "equipment") {
        this.indexCode = data.indexCode;
        this.startVideo(data.indexCode);
      }
    },
    //初始化加载数据的方法
    initData() {
      getEquipmentTree({
        equipmentType: "7",
        manufacturer: "1",
        type: "3",
      }).then((res) => {
        this.treeDataList = res.data;
      });
    },
    loadJsFunc() {
      return new Promise((resolve, reject) => {
        let arr = "//" + this.fileUrl + "/js/web-control-1.2.4.min.js";
        let script = document.createElement("script");
        script.type = "text/javascript";
        script.src = arr;
        document.getElementsByTagName("body")[0].appendChild(script);
        resolve("success");
      });
    },
    //关闭窗口
    destroyWnd() {
      this.oWebControl.JS_HideWnd();
    },
    // 创建插件实例，并启动本地服务建立websocket连接，创建插件窗口
    initPlugin() {
      let that = this;
      this.oWebControl = new WebControl({
        szPluginContainer: "playWnd",
        iServicePortStart: 15900,
        iServicePortEnd: 15900,
        szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11", // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: function () {
          that.initCount = 0;
          that.oWebControl.JS_SetWindowControlCallback = {
            cbIntegrationCallBack: that.cbIntegrationCallBack,
          };
          that.oWebControl
              .JS_StartService("window", {
                dllPath: "./VideoPluginConnect.dll",
              })
              .then(
                  function () {
                    that.oWebControl
                        .JS_CreateWnd(
                            "playWnd",
                            document.body.clientWidth * ((24 - that.tree_width) / 24),
                            document.body.clientHeight -
                            document.body.clientHeight * 0.09,
                            {
                              bEmbed: true,
                            }
                        )
                        // .JS_CreateWnd("playWnd", 530, 300)
                        .then(function () {
                          console.log("JS_CreateWnd success");
                          that.oWebControl
                              .JS_RequestInterface({
                                funcName: "getRSAPubKey",
                                argument: JSON.stringify({
                                  keyLength: 1024,
                                }),
                              })
                              .then(function (oData) {
                                if (oData.responseMsg.data) {
                                  that.pubKey = oData.responseMsg.data;
                                }
                              });
                          that.initFunc();
                        });
                  },
                  function () {
                  }
              );
        },
        cbConnectError: function () {
          that.oWebControl = null;
          $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
          WebControl.JS_WakeUp("VideoWebPlugin://");
          that.initCount += 1;
          if (that.initCount < 3) {
            setTimeout(function () {
              that.initPlugin();
            }, 3000);
          } else {
            alert("插件启动失败，请检查插件是否安装！");
            $("#playWnd")
                .html(`插件启动失败，请检查插件是否安装！<a style='color:red' href='http://${that.fileUrl}/plugin/VideoWebPlugin.exe'>点击下载</a>
              <br/> 保证安装成功之后启动失败处理方案：在Chrome浏览器地址栏搜索chrome://flags，然后在搜索框搜索Block insecure private network requests，最后将其Default改为Disabled。最后点击右下角Relaunch!
              `);
          }
        },
        cbConnectClose: function (bNormalClose) {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log("cbConnectClose");
          that.oWebControl = null;
          $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
          WebControl.JS_WakeUp("VideoWebPlugin://");
          that.initCount += 1;
          if (that.initCount < 3) {
            setTimeout(function () {
              that.initPlugin();
            }, 3000);
          } else {
            alert("插件启动失败，请检查插件是否安装！");
            $("#playWnd")
                .html(`插件启动失败，请检查插件是否安装！<a style='color:red' href='http://${that.fileUrl}/plugin/VideoWebPlugin.exe'>点击下载</a>
              <br/> 保证安装成功之后启动失败处理方案：在Chrome浏览器地址栏搜索chrome://flags，然后在搜索框搜索Block insecure private network requests，最后将其Default改为Disabled。最后点击右下角Relaunch!
              `);
          }
        },
      });
    },
    syncCameraInfo(data) {
      let that = this;
      // this.$modal.confirm('是否同步确认摄像机状态！').then(function() {
      that.loading = true;
      getCameraInfo({type: data}).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("同步摄像机信息成功！");
          this.loading = false;
        }
        // })
      });
    },
    //初始化信息
    initFunc() {
      console.log("初始化组件信息");
      //   拼接参数
      let _that = this;
      //删除字符串中的回车换行和空格
      //解析初始化时的playMode字段  写死初始化0
      var initFuncType = 0;
      if (0 == initFuncType) {
        if (!_that.JsonParam.hasOwnProperty("argument")) {
          _that.showCBInfo("init failed, param miss argument field");
        } else {
          if (_that.JsonParam.argument.hasOwnProperty("playMode")) {
            var playMode = _that.JsonParam.argument.playMode;
          }
          //如果包含加密处理，处理加密字段
          if (_that.JsonParam.argument.hasOwnProperty("encryptedFields")) {
            var enFields = _that.JsonParam.argument.encryptedFields;
            var strArray = new Array();
            strArray = enFields.split(",");
            for (var i = 0, len = strArray.length; i < len; i++) {
              if ("appkey" == strArray[i]) {
                if (_that.JsonParam.argument.hasOwnProperty("appkey")) {
                  var appkey = _that.JsonParam.argument.appkey;
                  appkey = setEncrypt(appkey);
                  _that.JsonParam.argument.appkey = appkey;
                }
              }

              if ("secret" == strArray[i]) {
                if (_that.JsonParam.argument.hasOwnProperty("secret")) {
                  var secret = _that.JsonParam.argument.secret;
                  secret = setEncrypt(secret);
                  _that.JsonParam.argument.secret = secret;
                }
              }
              if ("ip" == strArray[i]) {
                if (_that.JsonParam.argument.hasOwnProperty("ip")) {
                  var ip = _that.JsonParam.argument.ip;
                  ip = setEncrypt(ip);
                  _that.JsonParam.argument.ip = ip;
                }
              }
              if ("snapDir" == strArray[i]) {
                if (_that.JsonParam.argument.hasOwnProperty("snapDir")) {
                  var snapDir = _that.JsonParam.argument.snapDir;
                  snapDir = setEncrypt(snapDir);
                  _that.JsonParam.argument.snapDir = snapDir;
                }
              }
              if ("layout" == strArray[i]) {
                if (_that.JsonParam.argument.hasOwnProperty("layout")) {
                  var layout = _that.JsonParam.argument.layout;
                  layout = setEncrypt(layout);
                  _that.JsonParam.argument.layout = layout;
                }
              }
              if ("videoDir" == strArray[i]) {
                if (_that.JsonParam.argument.hasOwnProperty("videoDir")) {
                  var videoDir = _that.JsonParam.argument.videoDir;
                  videoDir = setEncrypt(videoDir);
                  _that.JsonParam.argument.videoDir = videoDir;
                }
              }
            }
          }
          //1.4.1及以上版本支持argument字段为json，以下版本argument必须为string
          var JsonArgument = _that.JsonParam.argument;
          // _that.JsonParam.argument = JSON.stringify(JsonArgument);
        }
        _that.oWebControl
            .JS_RequestInterface(_that.JsonParam)
            .then(function (oData) {
              // _that.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ""));
              // _that.UpdatePlayParamValue();
              // _that.oWebControl.JS_Resize(530, 300);
              let div = document.getElementById("divBox");
              const divH = div.clientHeight;
              const divW = div.clientWidth;
              _that.oWebControl.JS_Resize(divW, divH);
              // if (_that.type == "index") {
              //   _that.startVideo(
              //     _that.cameraIndexCode ? _that.cameraIndexCode : null
              //   );
              // }
            });
      } else {
        _that.requestInterface(param);
      }
    },
    // 判断字符串是否为json
    isJSON(str) {
      if (typeof str == "string") {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == "object" && obj) {
            return true;
          } else {
            this.showCBInfo("param is not the correct JSON message");
            return false;
          }
        } catch (e) {
          this.showCBInfo("param is not the correct JSON message");
          return false;
        }
      }
      console.log("It is not a string!");
    },
    // 设置窗口控制回调
    setCallbacks() {
      this.oWebControl.JS_SetWindowControlCallback({
        cbIntegrationCallBack: cbIntegrationCallBack,
      });
    },
    // 推送消息
    cbIntegrationCallBack(oData) {
      this.showCBInfo(JSON.stringify(oData.responseMsg));
    },
    // 显示接口返回的消息及插件回调信息
    showCBInfo(szInfo, type) {
      if (type === "error") {
        szInfo =
            "<div style='color: red;'>" +
            this.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") +
            " " +
            szInfo +
            "</div>";
      } else {
        szInfo =
            "<div>" +
            this.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") +
            " " +
            szInfo +
            "</div>";
      }
      $("#cbInfo").html(szInfo + $("#cbInfo").html());
    },
    // 格式化时间
    dateFormat(oDate, fmt) {
      var o = {
        "M+": oDate.getMonth() + 1, //月份
        "d+": oDate.getDate(), //日
        "h+": oDate.getHours(), //小时
        "m+": oDate.getMinutes(), //分
        "s+": oDate.getSeconds(), //秒
        "q+": Math.floor((oDate.getMonth() + 3) / 3), //季度
        S: oDate.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (oDate.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                  ? o[k]
                  : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return fmt;
    },
    requestInterface(value) {
      this.isJSON(value);
      var JsonParam = JSON.parse(value);
      var JsonArgument = JsonParam.argument;
      JsonParam.argument = JSON.stringify(JsonArgument);
      let _that = this;
      this.oWebControl.JS_RequestInterface(JsonParam).then(function (oData) {
        _that.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ""));
      });
    },
    //播放
    startVideo(data) {
      var param = {};
      //看是回放还是预览
      if (this.JsonParam.argument.playMode == 0) {
        param = this.startParam;
      } else {
        //赋值默认时间
        this.startBackParam.argument.startTimeStamp =
            Math.round(new Date() / 1000) - 60 * 60 * 24;
        this.startBackParam.argument.endTimeStamp = Math.round(
            new Date() / 1000
        );
        param = this.startBackParam;
      }
      if (data) {
        param.argument.cameraIndexCode = data;
      }
      this.requestInterface(JSON.stringify(param, null, 2));
    },
    //预览 默认为预览
    playPriew() {
      let _that = this;
      _that.showTimeDiv = false;
      _that.JsonParam.argument.playMode = 0;
      _that.oWebControl.JS_RequestInterface({funcName: "uninit"});
      _that.initFunc();
    },
    //回放
    playBack() {
      let _that = this;
      _that.showTimeDiv = true;
      _that.JsonParam.argument.playMode = 1;
      // _that.destroyWnd();
      _that.oWebControl.JS_RequestInterface({funcName: "uninit"});
      _that.initFunc();
    },
  },
};
</script>
<style>
.btn {
  margin: 0 10px;
}

.btn:hover {
  color: #409eff;
}

.btn.active {
  color: #409eff;
}

.redborder {
  border: 1px solid #ffcc00 !important;
}

.play-box {
  background-color: #262626;
  border: 2px solid #505050;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
</style>
<style lang="scss" scoped>
.videoList {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.video-item {
  position: relative;
  width: 15rem;
  height: 10rem;
  margin-right: 1rem;
  background-color: #000000;
}

.video-item-img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  height: 100%;
}

.video-item-img:after {
  content: "";
  display: inline-block;
  position: absolute;
  z-index: 2;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 3rem;
  height: 3rem;
  /* background-image: url("../assets/loading.png"); */
  background-size: cover;
  background-color: #000000;
}

.video-item-title {
  position: absolute;
  bottom: 0;
  color: #000000;
  background-color: #ffffff;
  line-height: 1.5rem;
  padding: 0.3rem;
  width: 14.4rem;
}

.baidumap {
  width: 100%;
  height: 100%;
  border: none;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

/* 去除百度地图版权那行字 和 百度logo */
.baidumap > .BMap_cpyCtrl {
  display: none !important;
}

.baidumap > .anchorBL {
  display: none !important;
}
</style>
